package com.carey.myblog.controller;

import com.carey.myblog.pojo.Comment;
import com.carey.myblog.pojo.User;
import com.carey.myblog.service.BlogService;
import com.carey.myblog.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class CommentController {
    @Autowired
    private CommentService commentService;

    @Value("${avatar}")
    private String avatar;

    @Autowired
    private BlogService blogService;

    @GetMapping("/comments/{blogId}")
    public String comments(@PathVariable Long blogId, Model model) {
        List<Comment> comment = commentService.listCommentByBlogId(blogId);
        model.addAttribute("comments", commentService.listCommentByBlogId(blogId));
        return "blog :: commentList";
    }

    @PostMapping("/comments")
    public String post(Comment comment, HttpSession session) {
        Long blogId = comment.getBlog().getId();
        comment.setBlog(blogService.getBlog(blogId));
        comment.setBlogId(blogId);
//        String loginStatus = (String) session.getAttribute("loginStatus");
//        if (loginStatus != null) {
//            String avatar = (String) session.getAttribute("avatar");
//            String openid = (String) session.getAttribute("openid");
//            comment.setAvatar(avatar);
//            comment.setAdminComment(1);
//            /*判断是否为管理员评论*/
//            if(adminOpenid.equals(openid)){
//                comment.setAdminComment(2);
//            }
//            System.out.println(openid);
//        } else {
//            comment.setAdminComment(0);
//            comment.setAvatar(avatar);
//        }
        //TODO 测试
        User user = (User) session.getAttribute("user");
        if (user!=null){
            comment.setAdminComment(2);
            comment.setAvatar(user.getAvatar());
        }else {
            comment.setAdminComment(0);
            comment.setAvatar(avatar);
        }
        commentService.saveComment(comment);
        return "redirect:/comments/" + blogId;
    }
}
